<?php
/**
 * 导出商家或店铺的 产品列表
 *
 * Author: lyun
 * Date: 2018/5/7
 * Created by Panxsoft.
 */

namespace App\Services\ExcelExporters;

use App\Models\Panx\Product;
use App\Services\Locale\Language;
use App\Services\Utils\TimeHelper;
use Illuminate\Database\Eloquent\Collection;
use Maatwebsite\Excel\Classes\LaravelExcelWorksheet;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Writers\LaravelExcelWriter;

class ProductExporter
{
    /** @const VIEW - 模板文件的名字 */
    const VIEW = 'excel.product';

    /** @const EXT - 导出的格式 */
    const EXT = 'xlsx';

    /** @const SHEET - excel分页的名字 */
    private $sheet = '商家产品';

    /**
     * @param Collection $data
     * @return mixed
     */
    public function transform(Collection $data)
    {
        $data = $data->transform(function(Product $product){
            $product->append(['brand_name', 'category_name', 'brand_series_name', 'cosmetic_material_name']);

            $product->product_tag_names = implode(',', $product->productTags->pluck('name')->all());

            return $product;
        });

        return $data->all();
    }

    /**
     * 返回 excel 文件名
     */
    public function filename()
    {
        return $this->sheet . TimeHelper::toFileSuffix();
    }

    /**
     * 直接导出excel
     *
     * @param Collection $data
     * @param $sheet_name
     * @throws \Maatwebsite\Excel\Exceptions\LaravelExcelException
     */
    public function export(Collection $data, ?string $sheet_name): void
    {
        $this->sheet = $sheet_name ?: $this->sheet;

        $data = $this->transform($data);

        /** @var Excel $excel */
        $excel = app('excel');

        $excel->create($this->filename(), function (LaravelExcelWriter $excel) use ($data) {
            $excel->sheet($this->sheet, function (LaravelExcelWorksheet $sheet) use ($data) {
                $sheet->setColumnFormat([
                    'C' => '@'
                ]);

                $sheet_name = $this->sheet;

                $sheet->loadView(self::VIEW, compact('data', 'sheet_name'));
            });
        })->export(self::EXT);
    }
}